<?php

namespace App\Models\V6;

use DB;
use Illuminate\Database\Eloquent\Model;

class MemberModel extends Model
{
    protected $table    = 'memberinfo';
    static $tb_member   = "memberinfo";   //会员表
    protected $primaryKey="UserID";
    private $defaultHeadImg;

    public function __construct()
    {
        $this->defaultHeadImg = env('API_HOST') . "/images/default-images/default-head-img.png";
    }

    /**
     * 注册用户
     * @param data 用户数据信息
     * @return intergel 用户ID
     * */
    public function register(array $data)
    {
        $dateTime = date_time();
        $data['ReleaseDate'] = $dateTime;
        $data['AddDate'] = $dateTime;
        $userId = DB::table(self::$tb_member)->insertGetId($data);
        return $userId;
    }

    /**
     * 获取用户信息
     * @param string mobile 用户的手机号
     * @param string appKey 用户的设备ID
     * @param boolean siVip 是否是VIP
     * @return Object
     * */
    public function get_member_info_by_mobile_key($mobile, $appKey, $isVip = false)
    {
        $memberInfo = $this->get_member_base_info($mobile, $appKey, $isVip);
        return $this->handle_member_info($memberInfo);
    }


    /**
     * 中间处理用户信息
     * */
    public function handle_member_info($memberInfo)
    {
        if (!$memberInfo) {

            return false;
        }
        unset($memberInfo->UserPassWord);
        $memberInfo->FilePath1  = change_member_head_img($memberInfo->FilePath1);
        $memberInfo->headImg    = $memberInfo->FilePath1;
        $memberInfo->head_img   = $memberInfo->FilePath1 ? $memberInfo->FilePath1 : $memberInfo->head_img;
        $memberInfo->isValid    = $this->judge_member_is_valid($memberInfo);
        $memberInfo->alias      = $memberInfo->UserName;
        $memberInfo->YourName   = emoji_text_decode($memberInfo->YourName);
        $memberInfo->NickName   = emoji_text_decode($memberInfo->NickName);
        $memberInfo->vipTimeIsValid   = strtotime($memberInfo->MemEndTime) > time() ? 1 : 0;

        return $memberInfo;
    }


    /**
     * 获取用户的基本信息
     * */
    public function get_member_base_info($mobile, $appKey, $isVip)
    {
        $memberInfo = DB::table(self::$tb_member)
            ->where('UserName', $mobile)
            ->where('AppKey', $appKey)
            ->where('DeleteMark', 1);
        $isVip ? $memberInfo = $memberInfo->where('States', 1) : '';
        $memberInfo = $memberInfo->first();
        return $memberInfo;
    }

    /**
     * 根据会员编号获取会员信息
     * */
    public function get_member_info_by_member_number($memberNumber)
    {
        $info = DB::table(self::$tb_member)
            ->where('MemNumber', $memberNumber)
            ->where('DeleteMark', 1)
            ->first();

        if (!$info) {
            $memberInfo = false;
        } else {
            $memberInfo = $this->get_member_info_by_mobile_key($info->UserName, $info->AppKey);
        }
        return $memberInfo;
    }

    /**
     * 根据手机号获取用户信息
     * */
    public function get_member_info_by_mobile($mobile)
    {
        $memberInfo = DB::table(self::$tb_member)
            ->select('AppKey')
            ->where('UserName', $mobile)
            ->where('DeleteMark', 1)
            ->first();
        if (!$memberInfo) {
            $memberInfo = false;
        } else {
            $memberInfo = $this->get_member_info_by_mobile_key($mobile, $memberInfo->AppKey);
        }
        return $memberInfo;
    }


    /**
     * 根据ID获得用户信息
     * @param userId 会员ID
     * */
    public function get_member_info_by_id($userId)
    {
        $memberInfo = DB::table(self::$tb_member)
            ->where('UserID', $userId)
            ->first();
        $memberInfo = $this->handle_member_info($memberInfo);
        return $memberInfo;
    }

    /**
     * 根据微信的unionId来获取用户信息
     * @param   string $unionId 微信开放平台unionId
     * @return  object
     * */
    public function get_member_info_by_unionid($unionId)
    {
        $memberInfo = DB::table(self::$tb_member)
            ->where("DeleteMark", 1)
            ->where("wx_unionid", $unionId)
            ->first();
        $memberInfo = $this->handle_member_info($memberInfo);
        return $memberInfo;
    }

    /**
     * 获得小程序用户信息
     * */
    public function get_miniapp_member_info($openId){

        $memberInfo = DB::table(self::$tb_member)
            ->where("DeleteMark", 1)
            ->where("mini_openid", $openId)
            ->first();

        $memberInfo = $this->handle_member_info($memberInfo);
        return $memberInfo;
    }

    /**
     * 获取用户的标签
     * */
    public function get_member_tags($userId)
    {
        $tags = DB::table('member_tag')->where('user_id', $userId)->pluck('tag_name');
        $tags = $tags ? $tags : [];
        return $tags;
    }


    /**
     * 判断用户是否有效
     *
     * */
    public function judge_member_is_valid($memberInfo)
    {
        $nowtime = date_time();
        $endtime = $memberInfo->MemEndTime;

        if ($memberInfo && $memberInfo->States == 1) {

            if (strtotime($nowtime) <= strtotime($endtime)) {

                return true;
            }
        }
        return false;
    }


    /**
     * 添加意见反馈
     * @arrSuggestion array $arrSuggestion 用户提交的建议信息
     * @return Object
     * */
    public function add_suggestion($arrSuggestion)
    {
        $date = date_time();
        $data = [
            'States' => 0,
            'DeleteMark' => 1,
            'ReleaseDate' => $date,
            'AddDate' => $date,
        ];
        $data = array_merge($arrSuggestion, $data);
        $result = DB::table('suggestion')->insert($data);
        return $result;
    }


    /**
     * 更新会员信息
     * @param array $arrMemberInfo 会员信息,其中必须包含两项之一 memberNumber或userid
     * @return Object
     * */
    public function update_member_info($arrMemberInfo)
    {
        $source = DB::table('memberinfo');
        if (isset($arrMemberInfo['UserID'])) {
            $source = $source->where('UserID', $arrMemberInfo['UserID']);
            unset($arrMemberInfo['UserID']);
        } elseif (isset($arrMemberInfo['MemNumber'])) {
            $source = $source->where('MemNumber', $arrMemberInfo['MemNumber']);
            unset($arrMemberInfo['MemNumber']);
        } else {
            return false;
        }
        $result = $source->update($arrMemberInfo);
        return $result;
    }


    /**
     * 改变用户的结束时间，必须在用户加入企业或移除后再调用
     * @param integer $userId 用户ID
     * */
    public function change_member_endtime($userId)
    {

        $sql = "SELECT  b.company_id,b.vip_end_date
              FROM      company_user a
              LEFT JOIN company b ON  b.company_id = a.company_id
              WHERE     a.user_id   = $userId
              AND       a.is_delete = 0
              AND       a.is_delete = 0
              GROUP BY  b.company_id ";
        $info   = DB::select($sql);
        $memberInfo = $this->get_member_info_by_id($userId);
        //计算所有时间的最大值
        $endTimes   = [strtotime($memberInfo->personal_end_time)];
        foreach($info as $v)
        {
            array_push($endTimes,strtotime($v->vip_end_date));
        }
        $maxTime    = current_date(max($endTimes));
        $this->update_member_info(['UserID'=>$userId,'MemEndTime'=>$maxTime]);
    }

    /**
     * 获得会员学习官关系信息
     * */
    public function get_member_drp_info($userId)
    {
        $sql = "SELECT
        b.MemNumber,
        b.SalesMoney,
        b.MemBalances,
        b.FinishMoney,
        b.DRPLevel,
        b.IDTree,
        b.ParentID,
        b.DRPID
        FROM memberinfo as a
        LEFT JOIN memberdrp as b ON  b.MemNumber = a.MemNumber AND  b.DeleteMark = 1
        WHERE a.UserID = $userId
        limit 1";
        $info = DB::select($sql);
        return $info[0];
    }


    /**
     * 绑定微信信息
     * @param integer $userId 用户ID
     * @param string $unionId 微信联合ID
     * @param string $openId 微信openId,
     * @param boolean $isGongzhonghao 是否是公众号
     * @param string $wxName 微信名称
     * @param string $headImg 头像图片
     * @return boolean
     * */
    public function bind_wx_info($userId, $unionId, $openId, $isGongzhonghao = true, $wxName = "", $headImg = "")
    {

        $data['wx_unionid'] = $unionId;
        $data['UserID']     = $userId;

        $wxName ? $data['NickName'] = $wxName : "";
        $headImg ? $data['head_img'] = $headImg : "";
        $isGongzhonghao ? $data['WeiXID'] = $openId : $data['app_openid'] = $openId;

        //删除 临时的ID

        DB::table('memberinfo')
            ->where('wx_unionid', $unionId)
            ->where('UserID','<>',$userId)
            ->update(['DeleteMark' => 0]);


        //修改用户信息
        $this->update_member_info($data);
        return true;
    }


    /**
     * 记录用户积分
     * @param integer $userId    用户ID
     * @param integer $integral  积分数量
     * @param integer $contentId 内容ID
     * @param string  $note      备注信息
     * */
    public function add_member_integral($userId,$integral,$contentId,$note)
    {
        $time   = date_time();
        $data   = [
            'user_id'       => $userId,
            'integral'      => $integral,
            'content_id'    => $contentId,
            'note'          => $note,
            'created_at'    => $time,
            'updated_at'    => $time
        ];
        $result = DB::table('member_integral')->insert($data);
        return $result;
    }


    public function get_online_time($userId)
    {
        $timeLength = DB::table('member_online_log')
            ->where('user_id',$userId)
            ->sum('time_length');
        return $timeLength;
    }

}